/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.JasperReport;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import merlion.crm.sopm.entity.SalesQuotation;
import javax.sql.DataSource;
import merlion.crm.sopm.entity.SalesOrder;
import merlion.frm.bpm.entity.Invoice;
import merlion.frm.bpm.entity.Receipt;
import merlion.scm.rmpm.entity.RawMaterialPurchaseOrder;
import net.sf.jasperreports.engine.JasperRunManager;

/**
 *
 * @author Kenn
 */
@ManagedBean(name = "jrManagerBean")
@ViewScoped
public class JasperReportManagerBean {

    @Resource(name = "merlionDataSource")
    private DataSource merlionDataSource;
    private SalesQuotation salesQuotation;
    private SalesOrder salesOrder;
    private Invoice salesInvoice;
    private Receipt salesReceipt;
    private RawMaterialPurchaseOrder rawMaterialPurchaseOrder;

    public JasperReportManagerBean() {
    }

    public byte[] getReportFile(Object report) {

        byte[] pdf = null;

        if (report instanceof SalesQuotation) {
            salesQuotation = (SalesQuotation) report;
            HashMap parameters = new HashMap();
            parameters.put("sqnumber", salesQuotation.getSqNumber());
            String reportPath = "/jasperreports/salesquotation.jasper";
            pdf = generateReport2(reportPath, parameters);
        }

        if (report instanceof SalesOrder) {
            salesOrder = (SalesOrder) report;
            HashMap parameters = new HashMap();
            parameters.put("soidstr", salesOrder.getSalesOrderIdStr());
            String reportPath = "/jasperreports/salesorder.jasper";
            pdf = generateReport2(reportPath, parameters);
        }

        if (report instanceof Invoice) {
            salesInvoice = (Invoice) report;
            HashMap parameters = new HashMap();
            parameters.put("invoicenumber", salesInvoice.getInvoiceId());
            String reportPath = "/jasperreports/invoice.jasper";
            pdf = generateReport2(reportPath, parameters);
        }

        if (report instanceof Receipt) {
            salesReceipt = (Receipt) report;
            HashMap parameters = new HashMap();
            parameters.put("receiptnumber", salesReceipt.getReceiptId());
            String reportPath = "/jasperreports/receipt.jasper";
            pdf = generateReport2(reportPath, parameters);
        }

        if (report instanceof RawMaterialPurchaseOrder) {
            rawMaterialPurchaseOrder = (RawMaterialPurchaseOrder) report;
            HashMap parameters = new HashMap();
            parameters.put("rawmaterialpo", rawMaterialPurchaseOrder.getPoNum());
            String reportPath = "/jasperreports/raw_material_PO.jasper";
            pdf = generateReport2(reportPath, parameters);
        }

        return pdf;
    }

    // edited by ZY
    public byte[] generateReport2(String reportPath, HashMap parameters) {

        byte[] pdf = null;

        try {
            
            // Test report path
            HttpServletRequest request =(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String path = request.getSession(true).getServletContext().getRealPath("/jasperreports");
            path = path.replace("\\", "\\\\") + "\\\\";
            parameters.put("SUBREPORT_DIR", path);
            
            
            InputStream reportStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(reportPath);
            pdf = JasperRunManager.runReportToPdf(reportStream, parameters, merlionDataSource.getConnection());

        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(JasperReportManagerBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        FacesContext.getCurrentInstance().responseComplete();
        return pdf;
    }

    public void generateSalesQuotationReport(ActionEvent event) throws SQLException {

        salesQuotation = (SalesQuotation) event.getComponent().getAttributes().get("salesQuotation");

        HashMap parameters = new HashMap();
        parameters.put("sqnumber", salesQuotation.getSqNumber());

        String reportPath = "/jasperreports/salesquotation.jasper";
        generateReport(reportPath, parameters);
    }

    public void generateSalesOrderReport(ActionEvent event) throws SQLException {

        salesOrder = (SalesOrder) event.getComponent().getAttributes().get("salesOrder");

        HashMap parameters = new HashMap();
        parameters.put("salesordernumber", salesOrder.getSalesOrderIdStr());

        String reportPath = "/jasperreports/salesorder.jasper";
        generateReport(reportPath, parameters);
    }

    public void generateSalesInvoiceReport(ActionEvent event) throws SQLException {

        salesInvoice = (Invoice) event.getComponent().getAttributes().get("invoice");

        HashMap parameters = new HashMap();
        parameters.put("invoicenumber", salesInvoice.getInvoiceId());
        System.out.println("Inv id: " + salesInvoice.getInvoiceId());
        String reportPath = "/jasperreports/invoice.jasper";
        generateReport(reportPath, parameters);
    }

    public void generateReceiptReport(ActionEvent event) throws SQLException {

        salesReceipt = (Receipt) event.getComponent().getAttributes().get("receipt");

        HashMap parameters = new HashMap();
        parameters.put("receiptnumber", salesReceipt.getReceiptId());

        String reportPath = "/jasperreports/receipt.jasper";
        generateReport(reportPath, parameters);
    }

    public byte[] generateReport(String reportPath, HashMap parameters) {

        byte[] pdf = null;

        try {
            InputStream reportStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(reportPath);
            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/pdf");

            pdf = JasperRunManager.runReportToPdf(reportStream, parameters, merlionDataSource.getConnection());
            outputStream.write(pdf);
            outputStream.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(JasperReportManagerBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        FacesContext.getCurrentInstance().responseComplete();
        return pdf;
    }

    //--------------------------------------------------------------------------
    //                              Getter and Setter
    //--------------------------------------------------------------------------
    public Invoice getSalesInvoice() {
        return salesInvoice;
    }

    public void setSalesInvoice(Invoice salesInvoice) {
        this.salesInvoice = salesInvoice;
    }

    public SalesOrder getSalesOrder() {
        return salesOrder;
    }

    public void setSalesOrder(SalesOrder salesOrder) {
        this.salesOrder = salesOrder;
    }

    public SalesQuotation getSalesQuotation() {
        return salesQuotation;
    }

    public void setSalesQuotation(SalesQuotation salesQuotation) {
        this.salesQuotation = salesQuotation;
    }

    public Receipt getSalesReceipt() {
        return salesReceipt;
    }

    public void setSalesReceipt(Receipt salesReceipt) {
        this.salesReceipt = salesReceipt;
    }
}
